<script setup>
import {reactive, ref, provide, onMounted} from "vue"
import DesignerHeader from "./Layout/DesignerHeader.vue"
import DesignerLeft from "./Layout/DesignerLeft.vue"
import DesignerPage from "./Layout/DesignerPage.vue"
import DesignerRight from "./Layout/DesignerRight.vue"
import {useRoute, useRouter} from "vue-router"

import test from "./test.js"
import * as api from "./api.js"
import clipScreen from "./Layout/clipScreen.js"

const route = useRoute()
const router = useRouter()

const state = reactive({
    active: null,
    elements: [],
    activeElementId: "",
    info: {},
    isLoading: false,
})

// 设计器
const designerPage = ref()
// 表单
const designerRight = ref()
const activeElementId = ref()
provide("activeElementId", activeElementId)

/**
 * 保存草稿
 */
const save = async () => {
    if (!state.elements || state.elements.length === 0) return $message.warning("请先设计模板")
    const ok = await $confirmSync("保存草稿", "保存草稿会覆盖之前的草稿，确定保存吗？")
    if (!ok) return
    localStorage.setItem("printTemplate" + route.query.id, JSON.stringify(state.elements))
}
/**
 * 预览
 */
const preview = () => {
    if (!state.elements || state.elements.length === 0) return $message.warning("请先设计模板")
    localStorage.setItem("printTemplatePreview" + route.query.id, JSON.stringify(state.elements))
    router.push(`/print-template-preview?id=${route.query.id}`)
}
/**
 * 使用草稿
 */
const useSaved = () => {
    const elements = localStorage.getItem("printTemplate" + route.query.id)
    if (elements) {
        console.log(elements)
        state.elements = JSON.parse(elements)
    } else {
        $message.warning("本地没有保存草稿")
    }
}

/**
 * 选中元素
 * @param element
 */
const setActive = (element) => {
    state.active = element
    activeElementId.value = element.id
}
/**
 * 子组件删除
 * @param element
 */
const onRemove = async (element) => {
    if (element.children && element.children.length > 0) {
        const ok = await $confirmSync("删除节点", "删除当前节点将会一并删除所有子节点，确定删除吗？")
        if (ok) {
            state.elements = state.elements.filter(el => el.id !== element.id)
        }
    } else {
        state.elements = state.elements.filter(el => el.id !== element.id)
    }
}

const customBlur = () => {
    activeElementId.value = null
}
/**
 * 加载数据
 */
const loadInfo = () => {
    state.isLoading = true
    api.GetProgramReport({id: route.query.id}).then(({data}) => {
        state.isLoading = false
        state.info = data
        state.elements = data.content ? JSON.parse(data.content) : []
    })
}
/**
 * 提交
 */
const beforeSubmit = async () => {
    console.log("提交", state.elements)
    if (!state.elements || state.elements.length === 0) return $message.warning("请先设计模板")
    const html = designerPage.value.getHtml()
    state.isLoading = true
    const base64 = await clipScreen(html, {width: 794, height: 1123})
    console.log(base64)
    const body = {...state.info, content: JSON.stringify(state.elements), image: base64}
    state.isLoading = false
    const {success} = await api.UpdateProgramReport(body);
    if (!success) return 0;
    $message.success("提交成功")
}

window.addEventListener("click", customBlur)
const designer = ref()
onMounted(() => {
    loadInfo()
    // 不这样处理 VueDraggable 在页面第一次加载完直接拖拽就会报错，不知道为啥，页面加载完立马点击一下页面，然后再拖拽就不会报错
    setTimeout(() => {
        designer.value.click()
    }, 300)
    // window.addEventListener("dblclick", beforeSubmit)
})

</script>

<template>
    <div v-loading="state.isLoading" ref="designer" class="Designer">
        <DesignerHeader :info="state.info" @preview="preview" @save="save" @useSaved="useSaved" @submit="beforeSubmit"/>
        <div class="container">
            <div class="left">
                <DesignerLeft :elements="state.elements" @active="setActive" />
            </div>
            <div ref="content" class="content">
                <DesignerPage ref="designerPage" :elements="state.elements" @active="setActive" @remove="onRemove" />
            </div>
            <div class="right">
                <DesignerRight v-if="state.active" ref="designerRight" :elem="state.active" />
                <template v-else>
                    <el-empty description="print-template-designer" />
                </template>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.Designer {
    width: 100vw;
    height: 100vh;
    background-color: #e9e9e9;

    .container {
        width: 100%;
        height: calc(100% - 80px);
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: flex-start;

        .left {
            width: 300px;
            height: 100%;
            background-color: #fff;
        }

        .content {
            width: calc(100% - 600px);
            height: 100%;
            overflow-y: auto;
            overflow-x: hidden;
            border: 1px solid #e9e9e9;
            box-sizing: border-box;
        }

        .right {
            background: #fff;
            height: 100%;
            width: 300px;
            border-top: 1px solid #e9e9e9;
            box-sizing: border-box;
        }
    }
}
</style>